<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="refreshLoading"
      @refresh="GetNextPageArticles"
      success-text="刷新成功"
    >
      <van-list
        :immediate-check="false"
        @load="GetNextPageArticles"
        v-model="loading"
        :finished="finished"
        finished-text="nothing anymore"
        :error.sync="error"
        error-text="Fail to request,pls click again."
      >
        <article-item
          v-for="item in articles"
          :key="item.art_id"
          :articleInfo="item"
        >
        </article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { NewArticlesAPI } from '@/api'
import ArticleItem from '@/views/Home/components/ArticleItem'
export default {
  // 子组件props是小驼峰，此时父组件可以写小驼峰也可以加横杠
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  data() {
    return {
      articles: [],
      preTimestamp: '',
      loading: false,
      finished: false,
      error: false,
      refreshLoading: false
    }
  },
  props: {
    channelId: [String, Number]
  },
  created() {
    this.getFirstPageArticle()
  },
  methods: {
    // 获取第一页的文章数据
    async getFirstPageArticle() {
      // 获取时间戳：Date.now()   new Date().valueOf()
      try {
        const { data } = await NewArticlesAPI(this.channelId, +new Date())
        this.articles = data.data.results
        // console.log(data)
        // 保存第一页的下一页的时间戳
        this.preTimestamp = data.data.pre_timestamp
      } catch (error) {
        if (error.response?.status === 400) {
          this.$toast.fail(error.response.data.message)
        } else {
          throw error
        }
      }
    },
    async GetNextPageArticles() {
      try {
        // if (Math.random() < 0.5) {
        //     throw new Error()
        // }
        // 1、发送请求
        const { data } = await NewArticlesAPI(this.channelId, this.preTimestamp)
        // 2、添加数据
        const results = data.data.results
        // console.log(results)
        // 如果下滑加载,将数据放在最后，如果下拉刷新，放在最前
        if (this.loading) {
          this.articles = [...this.articles, ...results]
        } else {
          this.articles = [...results, ...this.articles]
        }
        // 3、更新时间戳
        this.preTimestamp = data.data.pre_timestamp
        // 4、判断是否加载完毕
        if (!data.data.pre_timestamp) this.finished = true
      } catch (error) {
        this.error = true
      } finally {
        // 5、手动将loading改为false
        this.loading = false
        this.refreshLoading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
// less的&代表 父元素的选择器
// 1\定高  2\overflow：auto/scoll/overlay
// css伪元素  ::after
// ::-webkit-scrollbar   滚动槽
// ::-webkit-scrollbar-thumb   滚动块
.article-list {
  height: calc(100vh - 100px - 92px - 83px);
  overflow: auto;
  &::-webkit-scrollbar {
    width: 10px;
    background-color: transparent;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #3296fa;
    border-radius: 10px;
  }
}
</style>
